package com.wxg.demo.jsoup;

import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.wxg.utils.My;
import com.wxg.utils.MyDriver;
import com.wxg.utils.MyFileWriter;

/**
 * https://jsoup.org/(官网)
 * http://www.open-open.com/jsoup/(中文翻译)
 * http://www.importnew.com/21055.html(简单使用)
 * 
 * @author Wxg
 *
 */
public class JsoupDemo101 {
	
	public static final String WRAP_TAG = "emr"; //"span", emr, emrbreak;
	
	public static final String P1 = "<p>现病史:患者于半年余前无明显诱因下出现右上腹部疼痛，<span>呈持续性闷痛，</span>逐渐加重，开始无伴有皮肤黄染，未呈桔黄色，<b>无尿色变黄，</b>无呈浓茶样改变，间有发热、无畏寒，无寒战，在当地卫生所就诊，予中药及西药治疗（具体不详）明显好转，无明显皮肤搔痒，无返酸、嗳气，无呕吐，无腹泻。</p>";
	public static final String P2 = "<p style='width:80%;'>现病史:患者于半年余前无明显诱因下出现右上腹部疼痛，<span style='color:red;'>呈<b>持续性</b>闷痛，</span>逐渐加重，开始无伴有皮肤黄染，未呈桔黄色，<b>无尿色变黄，</b>无呈浓茶样改变，</p>";
	public static final String P3 = "<p style='width:80%;'>现病史:右上腹部疼痛，<span style='color:red;'>呈<b>持续性</b>闷痛，</span>逐渐加重，</p>";
	
	public static final Pattern TAG_REGEX = Pattern.compile("(<.+?>)(</.+>)");
	
	private static StringBuilder sbb = null;
	
	private static Stack<String> stack = null;
	
	public static void main(String[] args) {
		code104();
	}
	
	/**
	 * date: 2018年2月16日
	 * 如何将"不知道嵌套多少层"的html拆开呢?
	 */
	public static void code106(){
		Document doc = Jsoup.parse(P3);
		// 就是P标签
		Element eleRoot = doc.body().children().get(0);
		
		
	}
	
	private static void loop106(Node node){
		// 如果没有子元素(Node)说明是叶子节点
		if( node.childNodeSize() == 0 ){
			
		}else{}
	}
	
	
	
	/**
	 * Test : getStartAndEnd
	 */
	public static void code105(){
		Document doc = Jsoup.parse(P2);
		Element body = doc.body();
		Elements eles = body.getElementsByTag("p");
		
		for(Element ele : eles){
			String[] arr = getStartAndEnd( ele.clone().empty().toString() );
			System.out.println( arr[0] );
			System.out.println( arr[1] );
			System.out.println(ele.outerHtml());
		}
	}
	
	/**
	 * Test : loopChildNode
	 * 递归查找子元素
	 * 
	 */
	public static void code104(){
		Document doc = Jsoup.parse(P2);
		Element body = doc.body();
		Elements eles = body.getElementsByTag("p");
		sbb = new StringBuilder();
		stack = new Stack<String>();
		for(Element ele : eles){
			loopChildNode(ele);
		}
		System.out.println(sbb.toString());
		
		// 以下代码将`WRAP_TAG`标签去除
		Document doc2 = Jsoup.parse( sbb.toString() );
		Element body2 = doc2.body();
		Elements eles2 = body2.getElementsByTag( WRAP_TAG );
		if(null != eles2){
			for(Element ele : eles2){
				ele.before(ele.text());
				ele.remove();
			}
		}
		System.out.println( body2.toString() );
		
		// 测试WebDriver是否能够获取到`WRAP_TAG`包裹的元素
		MyFileWriter mfw = new MyFileWriter();
		mfw.writeb( Jsoup.parse( sbb.toString() ).toString() );
		mfw.close();
		WebDriver driver = MyDriver.getStaticDriver();
		System.out.println( mfw.getFilepath() );
		driver.get( My.fileUrl( mfw.getFilepath() ) );
		List<WebElement> eleList = driver.findElements(By.tagName( WRAP_TAG ));
		if(null != eleList){
			for(WebElement ele : eleList){
				System.out.printf( "\nx: %s, y: %s\n", ele.getLocation().x, ele.getLocation().y );
			}
		}
		MyDriver.closeStaticDriver();
	}
	
	/**
	 * 获得标签的Start 和 End
	 * 
	 * @param htmlStr
	 * @return
	 */
	private static String[] getStartAndEnd(String htmlStr){
		String[] arrStartAndEnd = new String[2];
		Matcher matcher = TAG_REGEX.matcher(htmlStr);
		if(matcher.matches()){
			arrStartAndEnd[0] = matcher.group(1);
			arrStartAndEnd[1] = matcher.group(2);
		}
		return arrStartAndEnd;
	}
	
	/**
	 * 递归查找子元素
	 * @param node
	 */
	private static void loopChildNode(Node node){
		String tagStart = "";
		String tagEnd = "";
		if(node.childNodeSize() == 0){
			// sbb.append( node.outerHtml() );
			sbb.append( addTagEveryWord( node.outerHtml(), WRAP_TAG ) );
			if( null == node.nextSibling() ){
				sbb.append( stack.pop() );
			}
		}else{
			String tagStr = ((Element)node.clone()).empty().toString();
			String[] arr = getStartAndEnd(tagStr);
			tagStart = arr[0];
			tagEnd = arr[1];
			sbb.append(tagStart);
			stack.push(tagEnd);
			
			List<Node> nodes = node.childNodes();
			for(Node n : nodes){
				loopChildNode(n);
			}
		}
	}
	
	private static String addTagEveryWord(String contents, String tagName){
		if(null == contents || null == tagName){
			return "";
		}
		StringBuilder sbb = new StringBuilder();
		char[] words = contents.toCharArray();
		if(null != words){
			for(char ch : words){
				sbb.append("<"+tagName+">");
				sbb.append(ch);
				sbb.append("</"+tagName+">");
			}
		}
		return sbb.toString();
	}
	
	
	public static void code103(){
		Document doc = Jsoup.parse(P1);
		Element body = doc.body();
		Elements eles = body.getElementsByTag("p");
		for(Element ele : eles){
			List<Node> nodeList = ele.childNodes();
			for(Node node : nodeList){
				if(node.childNodeSize() == 0){
					System.out.println( node.outerHtml() );
				}else{
					List<Node> nodes = node.childNodes();
				}
				System.out.println( node.hasParent() );
				System.out.println( node.outerHtml() );
				System.out.println("===");
				
//				List<Node> nodes = node.childNodes();
//				System.out.println( nodes );
				
//				if(nodes.size() != 0){
//					System.out.println( nodes.size() );
//				}else{
//					System.out.println( node.outerHtml() );
//				}
//				System.out.println( node.outerHtml() );
			}
		}
	}
	
	
	/**
	 * getAllElements(), children()
	 * 1) children() 只能拿到子标签,不能拿到纯文本
	 */
	public static void code102(){
		Document doc = Jsoup.parse(P1);
		Element body = doc.body();
		Elements eles = body.getElementsByTag("p");
		for(Element ele : eles){
			Elements allEles = ele.children(); // getAllElements(), children()
			for(Element eleA : allEles){
				System.out.println( eleA );
				System.out.println();
			}
		}
	}
	
	/**
	 * 1) Jsoup与WebDriver不同 : attr拿不到"outerHTML"<br>
	 * 2) 但是,Jsoup有方法"outerHtml()"<br>
	 * 
	 * 
	 * 
	 */
	public static void code101(){
		String html = "<div><p>Lorem ipsum.</p>";
		
		Document doc = Jsoup.parseBodyFragment(html);
//		System.out.println( doc );
		Element body = doc.body();
		System.out.println( body );
		System.out.println( body.attr("outerHTML") );
		Elements eles = body.getAllElements();
		for(Element ele : eles){
			System.out.println( ele );
			System.out.println( ele.attr("outerHTML") );
		}
	}
}
